#include <chrono>
#include <future>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
using namespace std::this_thread;
using namespace std::chrono;
#include <nanomsg/nn.h>
#include <nanomsg/reqrep.h>

#include "protobuf.h"
int client (const char *url, int ex, int gain)
{
    int fd;
    int rc;
    char *greeting;
    uint8_t msg[sizeof (uint32_t)];
    uint64_t start;
    uint64_t end;
    unsigned msec;

    // msec = atoi(msecstr);

    fd = nn_socket (AF_SP, NN_REQ);
    if (fd < 0) {
        fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));
        return (-1);
    }

    if (nn_connect (fd, url) < 0) {
        fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);        
    }

    // msec = htonl(msec);
    // memcpy (msg, &msec, sizeof (msec));

    // start = milliseconds ();
    Msg msg_proto;
    msg_proto.set_ex(ex);
    msg_proto.set_gain(gain);
    string str_proto;
    msg_proto.SerializeToString(&str_proto);

    cout << "ex " << ex << endl;
    cout << "gain " << gain << endl;



    if (nn_send (fd, str_proto.c_str(), str_proto.size(), 0) < 0) {
        fprintf (stderr, "nn_send: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);
    }

    // rc = nn_recv (fd, &msg, sizeof (msg), 0);
    // if (rc < 0) {
    //     fprintf (stderr, "nn_recv: %s\n", nn_strerror (nn_errno ()));
    //     nn_close (fd);
    //     return (-1);
    // }
    sleep_for(seconds(1));

    nn_close (fd);

    // end = milliseconds ();

    // printf ("Request took %u milliseconds.\n", (uint32_t)(end - start));
    return (0);
}

int main (int argc, char **argv)
{
    int rc;
    if (argc < 3) {
        fprintf (stderr, "Usage: %s <url> [-s|name]\n", argv[0]);
        exit (EXIT_FAILURE);
    }
    if (strcmp (argv[2], "-s") == 0) {
        // rc = server (argv[1]);
    } else {
        rc = client (argv[1], atoi(argv[2]), atoi(argv[3]));
    }
    exit (rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}